<?php


class MyAdminController extends Controller 
{
	public $params = array();
	public $with = array();
	public $scenario = null;
	protected $_model = null;
	
	
	public function init()
	{
		Yii::app()->theme = param('adminTheme');
		parent::init();
	}

	public function getViewPath($checkTheme=false){
		return Yii::getPathOfAlias('application.modules.'.$this->getModule($this->id)->getName().'.views.admin');
	}

	public function filters(){
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	public function accessRules(){
		return array(
			array(
				'allow',
				'expression' => 'Yii::app()->user->getState("isAdmin")',
			),
			array(
				'deny',
				'users'=>array('*'),
			),
		);
	}

	public function actionView($id){
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	public function loadModel($id = null){
		$model = new $this->modelName;

		if($id !== null){
			if($this->with){
				$model = $model->resetScope()->with($this->with)->findByPk($id);
			}
			else{
				$model = $model->resetScope()->findByPk($id);
			}
		}
		if($this->scenario){
			$model->scenario = $this->scenario;
		}

		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	public static function returnStatusHtml($data, $tableId, $onclick = 0, $ignore = 0){
		if($ignore && $data->id == $ignore){
			return '';
		}
		$url = Yii::app()->controller->createUrl("activate", array("id" => $data->id, 'action' => ($data->active==1?'deactivate':'activate') ));
		$img = CHtml::image(
					Yii::app()->theme->baseUrl.'/images/'.($data->active?'':'in').'active.png',
					Yii::t('common', $data->active?'Inactive':'Active'),
					array('title' => Yii::t('common', $data->active?'Deactivate':'Activate'))
				);
		$options = array();
		if($onclick){
			$options = array(
				'onclick' => 'ajaxSetStatus(this, "'.$tableId.'"); return false;',
			);
		}
		return '<div align="center">'.CHtml::link($img,$url, $options).'</div>';
		
	}

	public function actionActivate(){
        $field = isset($_GET['field']) ? $_GET['field'] : 'active';

		if(isset($_GET['id']) && isset($_GET['action'])){
			$action = $_GET['action'];
			$model = $this->loadModel($_GET['id']);
			if($this->scenario){
				$model->scenario = $this->scenario;
			}
			if($model){
				$model->$field = ($action == 'activate'?1:0);
				$model->update(array($field));
			}
		}
		if(!Yii::app()->request->isAjaxRequest){
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
		}
	}

	public function loadModelWith($with) {
		if(isset($_GET['id'])) {
			$model = new $this->modelName;
			if($this->scenario){
				$model->scenario = $this->scenario;
			}
			if($model===null){
				throw new CHttpException(404,'The requested page does not exist.');
			}
			return $model->resetScope()->with($with)->findByPk($_GET['id']);
		}
	}

	protected function performAjaxValidation($model){
		if(isset($_POST['ajax']) && $_POST['ajax']===$this->modelName.'-form'){
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	public function getMaxSorter(){
		$model = new $this->modelName;
		$maxSorter = Yii::app()->db->createCommand()
			->select('MAX(sorter) as maxSorter')
			->from($model->tableName())
			->queryScalar();
		$this->params['maxSorter'] = $maxSorter;
	}

	public function actionMove(){
		if(isset($_GET['id']) && isset($_GET['direction'])){
			$direction = isset($_GET['direction']) ? $_GET['direction'] : '' ;

			$model = $this->loadModel($_GET['id']);
			$catId = isset($_GET['catid']) ? $_GET['catid'] : '';

			if($model && ($direction == 'up' || $direction == 'down') ){
				$addWhere = '';
				if (!empty($catId) && $catId > 0) {
				    $addWhere = ' AND reference_category_id = "'.$catId.'"';
				}	
			    
				$sorter = $model->sorter;
				
				if($direction == 'up'){
					if($sorter > 1){
						$sql = 'UPDATE '.$model->tableName().' SET sorter="'.$sorter.'" WHERE sorter < "'.($sorter).'" '.$addWhere.' ORDER BY sorter DESC LIMIT 1';
						Yii::app()->db->createCommand($sql)->execute();
						$model->sorter--;
						$model->save();
					}
				}
				if($direction == 'down'){
					if (!empty($catId) && $catId > 0) {
					    $maxSorter = Yii::app()->db->createCommand()
						->select('MAX(sorter) as maxSorter')
						->from($model->tableName())
						->where('reference_category_id=:catid', array(':catid'=>$catId))
						->queryScalar();
					}
					else {
					    $maxSorter = Yii::app()->db->createCommand()
						->select('MAX(sorter) as maxSorter')
						->from($model->tableName())
						->queryScalar();
					    
					}
					
					if($sorter < $maxSorter){
						$sql = 'UPDATE '.$model->tableName().' SET sorter="'.$sorter.'" WHERE sorter > "'.($sorter).'" '.$addWhere.' ORDER BY sorter ASC LIMIT 1';
						Yii::app()->db->createCommand($sql)->execute();
						$model->sorter++;
						$model->save();
					}
				}
			}
		}
		if(!Yii::app()->request->isAjaxRequest){
			$this->redirect(isset($_GET['returnUrl']) ? $_GET['returnUrl'] : array('index'));
		}
	}

}

?>
